package com.sjy.mvvmdemo.roomdb.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager

/**
 * 操作入口（保持但例，持久化调用）
 */
@Database(entities = [UserEntity::class], version = 1)
abstract class UserDatabase : RoomDatabase() {
    abstract val mUserDao: UserDao

    companion object {
        @Volatile
        private var instance: UserDatabase? = null
        fun getInstance(context: Context): UserDatabase {
            return instance ?: synchronized(this) {
                instance ?: buildUserDatabase(context).also { instance = it }
            }
        }

        private fun buildUserDatabase(context: Context): UserDatabase {
            return Room
                .databaseBuilder(
                    context.applicationContext,
                    UserDatabase::class.java,
                    "sjy_user"//表名
                )
                .addCallback(object : RoomDatabase.Callback() {
                    //添加workManager管理测试
                    override fun onCreate(db: SupportSQLiteDatabase) {
                        super.onCreate(db)
                        val request = OneTimeWorkRequestBuilder<DbTestDataInit>().build()
                        WorkManager.getInstance().enqueue(request)
                    }
                })
//                .addMigrations(object : Migration(1, 2) {//数据1--2升级，数据2-1降级
//                    //版本升级/降级处理
//                    override fun migrate(database: SupportSQLiteDatabase) {
//                        //补充上升级要添加的列属性，
//                    }
//
//                })
//                .fallbackToDestructiveMigration()//未匹配，则删表重建
                .build()
        }

    }

}